<template>
  <el-form class="qr-code" align="center">
    <el-form-item class="qr-code__img">
      <qriously ref="qrcode" :value='value_code' :size='169' id="mycanvas"></qriously>
    </el-form-item>
    <el-form-item vertical-fill no-spacing>
      <!--<el-button-->
        <!-- @click="copyPic" -->
      <!-- &gt; -->
        <!--复制二维码-->
      <!--</el-button>-->
      <el-button
        type="primary"
        @click="saveImg"
      >
        下载二维码
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>

  export default {

    name: 'qr-code',

    props: ["editData"],

    inject: ['setDialogHeader'],

    data() {
      return {
        value_code: this.editData.domain,
      };
    },

    methods: {
      // 将canvas生成的二维码保存为图片
      saveImg() {
        let canvas = document.querySelector("#mycanvas>canvas");
        let imgSrc = canvas.toDataURL("image/png");
        let a = document.createElement("a");
        a.href = imgSrc;
        a.download = "drcQrcode";
        a.click();
      },
      copyPic() {
        const target = this.$refs.qrcode.$el.querySelector('canvas');

        let img = document.createElement('img');
        img.src = target.toDataURL();

        let div = document.createElement('div');
        div.contentEditable = true;
        div.appendChild(img);
        document.body.appendChild(div);

        this.getSelect(div);
        document.execCommand('copy');
        document.body.removeChild(div);
      },
      getSelect(element) {
        const doc = document;
        if (doc.body.createTextRange) {
          let range = document.body.createTextRange();
          range.moveToElementText(element);
          range.select();
        } else if (window.getSelection) {
          let selection = window.getSelection();
          let range = document.createRange();
          range.selectNodeContents(element);
          selection.removeAllRanges();
          selection.addRange(range);
        }
      }
    },
    created() {
      this.setDialogHeader('二维码');
    }
  };
</script>
